#include <iostream>
#include "udpserver.hpp"
void usage(std::string str)
{
    std::cout << "usage: " << str << "  server_ip server_port" << std::endl;
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        usage(argv[0]);
        exit(USAGE_ERROR);
    }
    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        LOG(FATAL, "socket error ,%s,%d\n", strerror(errno), errno);
        exit(SOCKET_ERROR);
    }
    struct sockaddr_in local; // struct sockaddr_in 系统提供的数据类型用于IPv4。local是变量，用户栈上开辟空间。
    bzero(&local, sizeof(local));
    local.sin_family = AF_INET;
    local.sin_port = htons(server_port); // port要经过网络传输给对面，先到网络，_port：主机序列-> 主机序列，转成网络序列
    // local.sin_addr.s_addr = inet_addr(_ip.c_str()); // "192.168.3.1" -> 字符串风格的点分十进制的IP地址 -> 4字节
    local.sin_addr.s_addr = inet_addr(server_ip.c_str());
    std::string message;
    while(true)
    {
        std::cout<<"please enter#";
        std::getline(std::cin,message);
        sendto(sockfd,message.c_str(),message.size(),0,(struct sockaddr* )&local,sizeof(local));
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        char buffer[1024];
        ssize_t n = recvfrom(sockfd,buffer,sizeof(buffer),0,(struct sockaddr*)&peer,&len);
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout<<"server echo#"<<buffer<<std::endl;
        }
    }
    return 0;
}